<template>
  <div class="table-pagination">
    <el-table
      :data="dataList"
      border
      :tree-props="{
        checkStrictly: false
      }"
      row-key="id"
      default-expand-all
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="showSelection" type="selection" width="55" />
      <el-table-column v-if="showIndex" type="index" width="55" :index="indexMethod" label="序号" align="center" />
      <el-table-column
        v-for="(item, index) in headList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        align="center"
      >
        <template v-if="item.slot" #default="{ row }">
          <component :is="item.render(row)" v-if="item.render" />
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            v-for="btn in layoutButtons"
            :key="btn"
            :type="buttonConfig[btn].type"
            size="small"
            @click="emits(buttonConfig[btn].event, row)"
          >
            {{ buttonConfig[btn].text }}
          </el-button>

          <slot />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="showPage"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      background
      layout="total, prev, pager, next"
      :total="total"
      @change="handleChange"
    />
  </div>
</template>

<script setup>

const props = defineProps({
  dataList: {
    type: Array,
    default: () => []
  },
  headList: {
    type: Array,
    default: () => []
  },
  page: {
    type: Number,
    default: 1
  },
  size: {
    type: Number,
    default: 20
  },
  total: {
    type: Number,
    default: 0
  },
  layout: {
    type: String,
    default: 'edit, delete, detail'
  },
  showIndex: {
    type: Boolean,
    default: true
  },
  showSelection: {
    type: Boolean,
    default: true
  },
  showPage: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits([
  'edit',
  'delete',
  'detail',
  'resetPassword',
  'change',
  'select'
])

const currentPage = ref(props.page)
const pageSize = ref(props.size)

const layoutButtons = computed(() => {
  return props.layout.split(',').map(item => item.trim())
})
const buttonConfig = {
  edit: { text: '编辑', type: 'primary', event: 'edit' },
  delete: { text: '删除', type: 'danger', event: 'delete' },
  detail: { text: '详情', type: 'info', event: 'detail' },
  resetPassword: { text: '重置密码', type: 'info', event: 'resetPassword' }
}

const indexMethod = (index) => {
  return index * props.page + 1
}

const handleChange = (page, size) => {
  emits('change', { page, size })
}

const handleSelectionChange = (val) => {
  emits('select', val)
}
</script>

<style lang="scss" scoped></style>
